package com.zd.springsecuritydemo.handler;

import com.alibaba.fastjson.JSON;
import com.zd.springsecuritydemo.response.ResponseResult;
import com.zd.springsecuritydemo.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 只处理授权异常
 * @author ZhangDong
 * @date 2024/1/7 19:26
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        ResponseResult<Object> responseResult = new ResponseResult<>(HttpStatus.FORBIDDEN.value(), "您的权限不足");
        // 处理异常
        WebUtils.renderString(response, JSON.toJSONString(responseResult));
    }
}
